const utils = require("./utils");
const transform = require("./transform");
const dispatchRequest = (config) => {
  config.headers = config.headers || {};
  // 先整合数据
  config.data = transform(config.data, config.headers, config.transformRequest);

  // 再扁平化整合请求头
  config.headers = Object.assign(
    config.headers.common || {},
    config.headers[config.method],
    config.headers
  );

  // 删掉请求头中无用数据
  utils.forEach(["common", "post", "put"], function (method) {
    if (config.headers[method]) {
      delete config.headers[method];
    }
  });
  console.log(config, "config");
  // 发送请求
  return config.adapter(config).then(
    function (response) {
      response.data = transform(
        response.data,
        response.headers,
        config.transformResponse
      );
      console.log(response, "返回的response");
      return response;
    },
    function (reason) {
      return Promise.reject(reason);
    }
  );
};

module.exports = dispatchRequest;
